﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TwitterProvider.cs" company="Catel development team">
//   Copyright (c) 2008 - 2012 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Catwitter.Providers.Twitter
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using LinqToTwitter;
    using Models;

    /// <summary>
    /// Social media provider for Twitter.
    /// </summary>
    public class TwitterProvider : SocialMediaProviderBase
    {
        #region Constructor & destructor
        /// <summary>
        /// Initializes a new instance of the <see cref="TwitterProvider"/> class.
        /// </summary>
        public TwitterProvider()
            : base("Twitter")
        {
        }
        #endregion

        #region Methods
        /// <summary>
        /// Gets the last 10 updates.
        /// </summary>
        /// <returns>
        /// 	<see cref="IEnumerable{ISocialMediaEntry}"/> containing all the updates.
        /// </returns>
        public override IEnumerable<ISocialMediaEntry> GetLast10Updates()
        {
            var updates = new List<ISocialMediaEntry>();

            var twitterCtx = new TwitterContext();

            var queryResults =
                from search in twitterCtx.Search
                where search.Type == SearchType.Search &&
                      search.Query == "#catel"
                select search;

            var srch = queryResults.Single();
            foreach (var tweet in srch.Results)
            {
                var entry = ConvertTwitterStatusToSocialMediaEntry(tweet);
                if (entry != null)
                {
                    updates.Add(entry);
                }
            }

            return updates;
        }

        /// <summary>
        /// Converts the twitter status object to social media entry.
        /// </summary>
        /// <param name="entry">The entry as twitter status.</param>
        /// <returns>
        /// New <see cref="ISocialMediaEntry"/> or <c>null</c> if the item could not be constructed.
        /// </returns>
        private ISocialMediaEntry ConvertTwitterStatusToSocialMediaEntry(SearchEntry entry)
        {
            //Bitmap photo = GetBitmapFromUrl(entry.Author.ProfileImageUrl);
            Uri photo = new Uri(entry.ProfileImageUrl);
            string author = entry.FromUserName;
            string message = entry.Text;
            DateTime timestamp = entry.CreatedAt.DateTime;
            string url = string.Format("http://www.twitter.com/{0}", entry.FromUserName);

            return new SocialMediaEntry(photo, author, message, timestamp, url, Name);
        }
        #endregion
    }
}